package com.lovo.atm.service.impl;

import com.lovo.atm.bean.AtmUserBean;
import com.lovo.atm.bean.MessageBean;
import com.lovo.atm.dao.IAtmDao;
import com.lovo.atm.dao.IMessgeDao;
import com.lovo.atm.dao.impl.IAtmDaoImpl;
import com.lovo.atm.dao.impl.IMessgeDaoImpl;
import com.lovo.atm.service.IAtmService;

public class IAtmServiceImpl implements IAtmService {
    private IAtmDao iAtmDao = new IAtmDaoImpl();

    private IMessgeDao iMessgeDao = new IMessgeDaoImpl();

    @Override
    public AtmUserBean Login(String name, String psw) {
        return iAtmDao.Login(name, psw);
    }

    @Override
    public AtmUserBean findByCode(String code) {
        return iAtmDao.findByName(code);
    }

    @Override
    public void saveMoney(String code, int count) {
        AtmUserBean userBean = iAtmDao.findByName(code);
        iAtmDao.update(code, count);
        iMessgeDao.addDeal(new MessageBean("存款", count, code));
    }

    @Override
    public boolean getMoney(String code, int count) {
        AtmUserBean userBean = iAtmDao.findByName(code);
        if (userBean.getCount() >= count) {
            iAtmDao.update(code, -count);
            iMessgeDao.addDeal(new MessageBean("取款", count, code));
        }
        return false;
    }

    @Override
    public String trans(String code, String targetCode, int count) {
        AtmUserBean user = iAtmDao.findByName(code);
        AtmUserBean taruser = iAtmDao.findByName(targetCode);
        if (taruser == null) {
            return "该用户不存在";
        }
        if (user.getCount() < count) {
            return "余额不足";
        }
        iAtmDao.update(code, -count);
        iAtmDao.update(targetCode, count);
        iMessgeDao.addDeal(new MessageBean("收到" + code + "转账", count, targetCode));
        iMessgeDao.addDeal(new MessageBean("转账给" + targetCode, count, code));
        return "转账成功";
    }
}
